package com.wensi.helper

import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.net.Uri
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.wensi.data.AppData
import com.wensi.lib_base.R

/**
 * 应用管理类
 */
object AppHelper {
    private lateinit var context: Context
    private lateinit var pm: PackageManager
    val allAppDataList = ArrayList<AppData>() // 所有应用的app信息
    val allAppViewList = ArrayList<View>() // 所有应用的View信息
    val allAppMarketList = ArrayList<String>() // 所有应用商店信息

    fun initAppHelper (context: Context) {
        this.context = context
        pm = context.packageManager
        loadApp ()

        loadAllPageView()

        loadAppStorePackageName()
    }
    // 加载所有的app
    private fun loadApp () {
        val intent = Intent(Intent.ACTION_MAIN, null)
        val flags = Intent.CATEGORY_LAUNCHER
        intent.addCategory(flags)
        val appInfo: List<ResolveInfo> = pm.queryIntentActivities(intent, 0)
        appInfo.forEachIndexed { _, resolveInfo ->
            allAppDataList.add(AppData(
                resolveInfo.activityInfo.packageName,
                resolveInfo.loadLabel(pm) as String,
                resolveInfo.loadIcon(pm),
                resolveInfo.activityInfo.name,
                resolveInfo.activityInfo.flags == ApplicationInfo.FLAG_SYSTEM))

        }
    }

    // 初始化加载pagerview
    private fun loadAllPageView() {
        // 遍历所有app对象的数量
        for (i in 0 until getPageSize()) {
            // 最外层 FrameLayout
            val rootView = View.inflate(context, R.layout.layout_app_manager_item, null) as ViewGroup
            // 第一层，仅一个LinearLayout
            for (j in 0 until rootView.childCount) {
                //  第二层，有6个LinearLayout
                val childJ = rootView.getChildAt(j) as ViewGroup // 6个LinearLayout其中一个
                // 第三层，有4个LinearLayout
                for (k in 0 until childJ.childCount) {
                    // 第四层，有ImageView + TextView
                    val childK = childJ.getChildAt(k) as ViewGroup // 4个LinearLayout其中一个
                    val img = childK.getChildAt(0) as ImageView
                    val text = childK.getChildAt(1) as TextView
                    // 计算当前的下表
                    val indexCurrent = i * 24 + j * 4 + k
                    if (indexCurrent < allAppDataList.size) {
                        img.setImageDrawable(allAppDataList[indexCurrent].appIcon)
                        text.text = allAppDataList[indexCurrent].appName

                        // 设置点击事件
                        childK.setOnClickListener {
                            intentApp(allAppDataList[indexCurrent].packName)
                        }
                    }
                }
            }

            allAppViewList.add(rootView) // 塞进列表
        }
    }

    private fun loadAppStorePackageName() {
        val stores = context.resources.getStringArray(R.array.AppMarketArray)
        stores.forEachIndexed { _, s ->
            allAppMarketList.add(s)
        }
    }

    fun getPageSize(): Int {
        return allAppDataList.size / 24 + 1
    }

    /** 启动app */
    fun launcherApp(appName: String): Boolean {
        if (allAppDataList.size > 0) {
            allAppDataList.forEach {
             if(it.appName == appName) {
                 intentApp(it.packName)
                 return true
             }
            }
        }
        return false
    }

    /** 卸载app */
    fun unInstallApp(appName: String): Boolean {
        if (allAppDataList.size > 0) {
            allAppDataList.forEach {
                if(it.appName == appName) {
                    intentUnInstallApp(it.packName)
                    return true
                }
            }
        }
        return false
    }

    // 具体实现 app启动
    private fun intentApp (packageName: String) {
        val intent = pm.getLaunchIntentForPackage(packageName)
        intent?.apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(this)
        }

    }
    // 具体实现 app卸载
    private fun intentUnInstallApp (packageName: String) {
        val intent = Intent(Intent.ACTION_DELETE)
        intent.data = Uri.parse("package:$packageName")
        intent?.apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(this)
        }

    }

    // 跳转到应用商店
    private fun intentAppStore(packageName: String, marketPackageName: String) {
        val uri: Uri = Uri.parse("market://details?id=$packageName")
        val intent = Intent(Intent.ACTION_VIEW, uri)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        intent.setPackage(marketPackageName)
        context.startActivity(intent)
    }

    // 获得非系统应用
    fun getNoSystemApp(): List<AppData> {
        return allAppDataList.filter { !it.isSystemApp }
    }
    // 跳转到应用商店
    fun intentAppStore(appName: String): Boolean {
        allAppDataList.forEachIndexed { _, appData ->
            if (allAppMarketList.contains(appData.packName)) {
                // 跳转到应用市场
                if (allAppDataList.size > 0) {
                    allAppDataList.forEach {
                        if(it.appName == appName) {
                            intentAppStore(it.packName, appData.packName)
                            return true
                        }
                    }
                }
                return true
            }
        }

        return false
    }
}